<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规格名称·" prop="productRuleName">
        <el-input
          v-model="queryParams.productRuleName"
          placeholder="请输入规格名称·"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类名称·" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          placeholder="请输入分类名称·"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:productRule:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:productRule:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:productRule:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:productRule:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productRuleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="productRuleId" />
      <el-table-column label="规格名称" align="center" prop="productRuleName" />
      <el-table-column label="分类名称" align="center" prop="typeName" />
      <el-table-column label="规格" align="center">
        <template slot-scope="scope">
          <div v-html="scope.row.attr"></div>
        </template>
      </el-table-column>
      <el-table-column label="规格详情" align="center">
        <template slot-scope="scope">
          <div v-html="scope.row.attrValues"></div>
        </template>
      </el-table-column>
      <el-table-column label="规格状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:productRule:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:productRule:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品规格对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="" prop="typeId">
          <div class="block">
            <span class="demonstration">三级下拉</span>
            <el-cascader
              @change="getTypeValue"
              v-model="typeValue"
              :options="typeList"
              :props="{label:'typeName',value:'typeId'}"
            ></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="规格名称·" prop="productRuleName">
          <el-input v-model="form.productRuleName" placeholder="请输入规格名称·" />
        </el-form-item>
        <el-form-item label="规格状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="rultAttr">
<!--          <el-input v-model="form.rultAttr" type="textarea" placeholder="请输入内容" />-->
          <div>
            <div v-for="(attr,index) in this.attrValues">
              <el-row>
                <el-col>
                  <el-tag
                    :key="attr.key"
                    closable
                    :disable-transitions="false"
                    @close="delAttr(attr.key)">
                    {{attr.key}}
                  </el-tag>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-tag
                    :key="val"
                    v-for="val in attr.values"
                    closable
                    :disable-transitions="false"
                    @close="delVal(attr.key, val)">
                    {{val}}
                  </el-tag>
                  <el-button v-show="attr.addValButStatus" size="mini" @click="addVal(index)">新增</el-button>
                  <el-input v-show="attr.addValInpStatus" v-model="attrValue" placeholder="请输入属性" size="mini" style="width: 150px" @blur="valSubmit(attr.key,index)"></el-input>
                </el-col>
              </el-row>
            </div>
<!--            <div>标题</div>-->
<!--            <div>内容</div>-->
          </div>
        </el-form-item>
      </el-form>
      <el-button v-show="attrButStatus" @click="showFormAttr">添加规格信息</el-button>
      <el-form v-show="attrFormStatus" :inline="true" :model="attrForm" class="demo-form-inline">
        <el-form-item label="规格名称">
          <el-input v-model="attrForm.key" placeholder="请输入规格名称"></el-input>
        </el-form-item>
        <el-form-item label="规格属性">
          <el-input v-model="attrForm.value" placeholder="请输入规格属性"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="attrSumbit">提交</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProductRule, getProductRule, delProductRule, addProductRule, updateProductRule } from "@/api/product/productRule";
import { listType } from "@/api/product/type"

export default {
  name: "ProductRule",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      attrFormStatus: false,
      attrButStatus: true,
      addValButStatus: true,
      addValInpStatus: false,
      attrValue: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品规格表格数据
      productRuleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productRuleName: null,
        typeName: null
      },
      // 表单参数
      form: {

      },
      attrForm: {
        key: '',
        value: ''
      },
      typeList: [],
      typeValue: [],
      attrValues: [],
      // 表单校验
      rules: {
        productRuleName: [
          { required: true, message: "规格名称·不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "规格状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getListType();
  },
  methods: {
    getTypeValueTo(typeList) {
      typeList.forEach((type) => {
        if (type.children != null){
          this.getTypeValueTo(type.children)
        }
        if (this.typeValue[0] == type.typeId && type.parentId != 0){
          var typeIds = this.typeValue.toString()
          typeIds = type.parentId + "," + typeIds
          this.typeValue = typeIds.split(",")
        }
      })
    },
    /** 查询类型列表 */
    getListType() {
      this.loading = true;
      listType(this.queryParams).then(response => {
        this.typeList = this.handleTree(response.data, "typeId", "parentId");
        this.loading = false;
      });
    },
    /** 属性提交 */
    valSubmit(attrKey,attrIndex){
      if(this.attrValue==''){
        this.$message.warning("属性不可以为空");
        return;
      }
      for(var index in this.attrValues) {
        if (this.attrValues[index].key == attrKey) {
          var values = this.attrValues[index].values;
          var valIndex = values.indexOf(this.attrValue);
          if(valIndex > -1){
            this.$message.warning("属性已经存在");
            return;
          }
          this.attrValues[index].values.push(this.attrValue)
        }
      }
      this.attrValue = '';
      this.attrValues[attrIndex].addValInpStatus=false;
      this.attrValues[attrIndex].addValButStatus=true;
    },
    /** 新增属性 */
    addVal(index){
      this.attrValues[index].addValInpStatus=true;
      this.attrValues[index].addValButStatus=false;
    },
    /** 删除属性 */
    delVal(attrKey, val) {
      var deleteIndex = -1;
      //第一层循环负责找到规格的对象
      for(var index in this.attrValues) {
        if (this.attrValues[index].key == attrKey) {
          //attr 就是规格的对象
          var attr = this.attrValues[index];
          //第二层 循环负责找到 属性所在位置
          for (var valIndex in attr.values) {
            if (attr.values[valIndex] == val) {
              deleteIndex = valIndex;
            }
          }
          //删除属性
          if (deleteIndex > -1) {
            attr.values.splice(deleteIndex, 1)
          }
        }
      }
    },
    /** 删除规格 */
    delAttr(attrValue){
      var attrIndex = -1
      for (var index in this.attrValues) {
        if (this.attrValues[index].key = attrValue) {
          attrIndex = index;
        }
      }
      if (attrIndex !== -1) {
        this.attrValues.splice(attrIndex, 1)
      }
    },
    /** 商品规格详情 */
    attrSumbit() {
      if(this.attrForm.key=='' || this.attrForm.value =='' ){
        this.$message.warning("规格信息不可以为空")
        return;
      }
      //判断是否有重复规格 如果有重复规格进行添加
      for(var index in this.attrValues){
        if(this.attrValues[index].key == this.attrForm.key){
          if (this.attrValues[index].values.indexOf(this.attrForm.value) > -1){
            this.$message.warning("["+this.attrForm.key+"]规格属性已经含有["+this.attrForm.value+"]")
            return
          }
          this.attrValues[index].values.push(this.attrForm.value)
          this.attrValues[index].addValInpStatus = true
          this.attrForm = {
            key: '',
            value: ''
          };
          this.showAddAttr()
          return;
        }
      }
      //如果没有重复的创建新的规格对象
      var attr = {
        key: this.attrForm.key,
        values:[this.attrForm.value],
        addValButStatus: true
      }
      this.attrValues.push(attr)
      this.attrForm = {
        key: '',
        value: ''
      };
      this.showAddAttr()
    },
    showFormAttr() {
      this.attrFormStatus = true
      this.attrButStatus = false
    },
    showAddAttr() {
      this.attrFormStatus = false
      this.attrButStatus = true
    },
    /** 查询商品规格列表 */
    getList() {
      this.loading = true;
      listProductRule(this.queryParams).then(response => {
        var rows = response.rows;
        rows.forEach(row =>{
          var rultAttr = JSON.parse(row.rultAttr);
          var attrHtml = "";
          var attrValuesHtml = "";
          //进行循环 rultAttr
          rultAttr.forEach(attr =>{
            attrHtml+="<p>"+attr.key+"</p>";
            var  values = attr.values;
            attrValuesHtml+="<p>"
            values.forEach((value,status = false)=>{
              if(status){
                attrValuesHtml+=","}else {status = true}
              attrValuesHtml += value
            })
            attrValuesHtml+="</p>"
          })
          row.attr = attrHtml;
          row.attrValues = attrValuesHtml;
        })
        this.productRuleList = rows
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productRuleId: null,
        rultAttr: null,
        status: "0",
        revision: null,
        createdBy: null,
        createdTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
      this.typeValue = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productRuleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品规格";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productRuleId = row.productRuleId || this.ids
      getProductRule(productRuleId).then(response => {
        this.form = response.data;
        this.typeValue.push(Number(response.data.typeId))
        this.getTypeValueTo(this.typeList,Number(response.data.typeId))
        this.attrValues = JSON.parse(this.form.rultAttr);
        this.open = true;
        this.title = "修改商品规格";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.typeId = this.typeValue[this.typeValue.length -1]
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productRuleId != null) {
            this.form.rultAttr = JSON.stringify(this.attrValues);
            updateProductRule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.attrValues = []
              this.getList();
            });
          } else {
            this.form.rultAttr = JSON.stringify(this.attrValues);
            addProductRule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.attrValues = []
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productRuleIds = row.productRuleId || this.ids;
      this.$modal.confirm('是否确认删除商品规格编号为"' + productRuleIds + '"的数据项？').then(function() {
        return delProductRule(productRuleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/productRule/export', {
        ...this.queryParams
      }, `productRule_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
